package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsCouponMapper;
import com.qf.pojo.DtsCoupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    private DtsCouponMapper couponMapper;

    @Override
    public IPage<DtsCoupon> list(Integer id, String name,
                                Integer page, Integer limit,
                                String sort, String order) {

        IPage<DtsCoupon> iPage = new Page<>(page, limit);
        QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("deleted",0);
        if (!StringUtils.isEmpty(id)){
            queryWrapper.eq("id",id);
        }
        if (!StringUtils.isEmpty(name)){
            queryWrapper.like("name",name);
        }

        if ("asc".equalsIgnoreCase(order)){
            queryWrapper.orderByAsc(sort);
        } else {
            queryWrapper.orderByDesc(sort);
        }

        IPage<DtsCoupon> dtsCouponIPage = couponMapper.selectPage(iPage, queryWrapper);
        return dtsCouponIPage;
    }

    @Override
    public DtsCoupon findOneById(Integer id) {
        List<DtsCoupon> dtsCoupons = couponMapper.selectList(null);
        for (int i = 0; i < dtsCoupons.size(); i++) {
          if (dtsCoupons.get(i).getId()==id){
              return dtsCoupons.get(i);
          }
        }
       // DtsCoupon dtsCoupon = couponMapper.selectById(id);
       return null;
    }

    @Override
    public DtsCoupon addOne(DtsCoupon coupon) {
        coupon.setAddTime(new Date());
        coupon.setDeleted(false);
        coupon.setUpdateTime(new Date());
        int insert = couponMapper.insert(coupon);
        if (insert==0){
            throw  new RuntimeException("添加失败！");
        }
        return coupon;
    }

    @Override
    public DtsCoupon updateOne(DtsCoupon dtsCoupon) {
        dtsCoupon.setUpdateTime(new Date());
        dtsCoupon.setStatus(0);
        int i = couponMapper.updateById(dtsCoupon);
        if (i==0){
            throw new RuntimeException("修改错误！");
        }
        return dtsCoupon;
    }

    @Override
    public void deleteOne(DtsCoupon dtsCoupon) {
        couponMapper.deleteById(dtsCoupon);
    }
}
